<template>
  <div class="login-container">
    <el-row>
      <el-col class="left hidden-md-and-down" :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
        <img v-show="showLogo" alt="" class="left-logo" src="../../assets/images/logo.png" />
        <div class="left-inner">
          <div class="left-title">欢迎使用工程报告写作平台</div>
          <div class="left-subtitle">AI编写可行性研究报告、项目申请报告。</div>
          <div class="left-intro">告诉我新建项目的基础信息，帮你一键生成复杂且详细的报告方案，还可以生成word提供下载。</div>
          <swiper />
        </div>
      </el-col>

      <el-col class="right" :lg="12" :md="24" :sm="24" :xl="12" :xs="24">
        <el-form
          ref="form"
          class="login-form"
          label-position="right"
          label-width="95px"
          :model="isRegister ? registerForm : form"
          :rules="rules"
        >
          <!-- 右上角注册/登录切换按钮 -->
          <div v-if="isRegister" class="register-button" @click="handleToLogin"><div class="register-button-inner">登录</div></div>
          <div v-else class="register-button" @click="handleToRegister"><div class="register-button-inner">注册</div></div>

          <div class="title">{{ isRegister ? '用户注册' : '用户登录' }}</div>

          <!-- 登陆表单 -->
          <span v-if="!isRegister">
            <el-form-item label="姓名：" prop="username">
              <el-input v-model.trim="form.username" placeholder="请输入用户名" tabindex="1" type="text" />
            </el-form-item>

            <el-form-item label="密码：" prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model.trim="form.password"
                placeholder="请输入密码"
                tabindex="2"
                :type="passwordType"
              />
              <span v-if="passwordType === 'password'" class="show-password" @click="handlePassword">
                <vab-icon :icon="['fas', 'eye-slash']" />
              </span>
              <span v-else class="show-password" @click="handlePassword">
                <vab-icon :icon="['fas', 'eye']" />
              </span>
            </el-form-item>
          </span>

          <!-- 注册表单 -->
          <span v-else>
            <el-form-item label="姓名：" prop="username">
              <el-input v-model.trim="registerForm.username" placeholder="请输入用户名" tabindex="1" type="text" />
            </el-form-item>

            <el-form-item label="邮箱：" prop="email">
              <el-input v-model.trim="registerForm.email" placeholder="请输入邮箱" tabindex="1" type="email" />
            </el-form-item>

            <el-form-item label="密码：" prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model.trim="registerForm.password"
                placeholder="请输入密码"
                tabindex="2"
                :type="passwordType"
              />
              <span v-if="passwordType === 'password'" class="show-password" @click="handlePassword">
                <vab-icon :icon="['fas', 'eye-slash']" />
              </span>
              <span v-else class="show-password" @click="handlePassword">
                <vab-icon :icon="['fas', 'eye']" />
              </span>
            </el-form-item>

            <el-form-item label="重复密码：" prop="password2">
              <el-input ref="password2" v-model.trim="registerForm.password2" placeholder="请重复密码" tabindex="2" type="password" />
            </el-form-item>
          </span>

          <!-- 重置密码 -->
          <div v-show="!isRegister" style="text-align: right">
            <el-button type="text" @click="handleReset">密码重置</el-button>
          </div>
          <!--          <el-button class="login-btn" :loading="loading" type="primary" @click="handleLogin">登录</el-button>-->

          <!-- 注册按钮 -->
          <img v-if="isRegister" alt="" class="login-btn" src="@/assets/images/register-button.png" @click="handleRegister" />

          <!-- 登录按钮 -->
          <img v-else alt="" class="login-btn" src="@/assets/images/login-button.png" @click="handleLogin" />

          <!-- 条款 -->
          <el-checkbox v-model="agree" class="agree-button">
            勾选此处代表您已阅读并同意以下条款：
            <br />
            1.本程序生成的所有内容均由AI（人工智能）编写，绝大部分数据来源于网络，请您仔细核对所生成内容的准确性。本公司对所生成内容的质量和细节概不负责。
            <br />
            2.严禁使用本程序操作有关任何违反法律法规的内容、严禁使用本程序上传或编辑机密性内容，如违反并造成了损失或纠纷与本公司无关。
          </el-checkbox>
        </el-form>
      </el-col>
    </el-row>

    <!-- 密码重置 -->
    <password-reset ref="resetDialog" />
  </div>
</template>

<script>
  import { isPassword, isEmail } from '@/utils/validate'
  import 'element-ui/lib/theme-chalk/display.css'
  import Swiper from '@/components/Swiper.vue'
  import { register } from '@/api/user'
  import PasswordReset from '@/views/login/components/PasswordReset.vue'

  export default {
    name: 'Login',
    components: { PasswordReset, Swiper },
    directives: {
      focus: {
        inserted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    data() {
      const validateusername = (rule, value, callback) => {
        if ('' === value) {
          callback(new Error('用户名不能为空'))
        } else {
          callback()
        }
      }
      const validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('请输入正确的邮箱'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          callback(new Error('密码不能少于6位'))
        } else {
          callback()
        }
      }
      const validatePassword2 = (rule, value, callback) => {
        if (value !== this.registerForm.password) {
          callback(new Error('密码不一致'))
        } else {
          callback()
        }
      }
      return {
        nodeEnv: process.env.NODE_ENV,
        title: this.$baseTitle,
        form: {
          username: '',
          password: '',
        },
        registerForm: {
          username: '',
          password: '',
          email: '',
          password2: '',
        },
        rules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              validator: validateusername,
            },
          ],
          email: [
            {
              required: true,
              trigger: 'blur',
              validator: validateEmail,
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
          password2: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword2,
            },
          ],
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        // timeOutID: null,
        agree: false,
        isRegister: false,
        showLogo: true,
      }
    },
    watch: {
      $route: {
        handler(route) {
          this.redirect = (route.query && route.query.redirect) || '/'
        },
        immediate: true,
      },
    },
    created() {
      document.body.style.overflow = 'hidden'
    },
    beforeDestroy() {
      document.body.style.overflow = 'auto'
      // clearTimeout(this.timeOutID)
    },
    mounted() {
      // this.$baseMessage('msg', 'success')
      // this.form.username = 'admin'
      // this.form.password = '123456'
      // window.onload = function () {
      // setTimeout(function () {
      //   window.focus()
      //   window.blur()
      //   alert(1)
      // }, 3000)
      // }
      window.addEventListener('resize', () => {
        document.querySelector('.left-logo').style.width = `${window.innerHeight * 0.32}px`
        // this.showLogo = window.innerHeight >= 700
      })
    },
    methods: {
      handleToLogin() {
        this.passwordType = 'password'
        this.isRegister = false
        this.$refs.form.clearValidate()
        this.registerForm = {
          username: '',
          password: '',
          email: '',
        }
      },
      handleToRegister() {
        this.passwordType = 'password'
        this.isRegister = true
        this.$refs.form.clearValidate()
        this.agree && (this.agree = false)
        this.form = {
          username: '',
          password: '',
        }
      },
      handlePassword() {
        this.passwordType === 'password' ? (this.passwordType = '') : (this.passwordType = 'password')
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        console.log(111)
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (!this.agree) {
              this.$baseNotify('登陆前请勾选协议')
              return
            }
            this.loading = true
            this.$store
              .dispatch('user/login', this.form)
              .then(() => {
                const routerPath = this.redirect === '/404' || this.redirect === '/401' ? '/' : this.redirect
                this.$router.push(routerPath).catch(() => {})
                this.loading = false
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            return false
          }
        })
      },
      handleRegister() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            if (!this.agree) {
              this.$baseNotify('请勾选协议')
              return
            }
            const param = {
              username: this.registerForm.username,
              password: this.registerForm.username,
              email: this.registerForm.username,
            }
            register(param)
              .then((res) => {
                console.log('register', res)
                const h = this.$createElement
                this.$notify({
                  title: '注册成功',
                  message: h('i', { style: 'color: teal' }, '注册成功，请耐心等待管理员审批'),
                })
                this.handleToLogin()
              })
              .catch((e) => {
                console.log(e)
              })
          }
        })
      },
      handleReset() {
        this.$refs.resetDialog.showDialog()
      },
    },
  }
</script>

<style lang="scss" scoped>
  .login-container {
    height: 100vh;
    min-height: 500px;
    width: 100%;
    background: url('~@/assets/login_images/background.jpg') no-repeat;
    background-size: cover;

    .left {
      height: 100vh;
      position: relative;

      .left-logo {
        width: 30%;
        position: absolute;
        top: 2%;
        left: 2%;
        z-index: 1;
      }

      .left-inner {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);

        .left-title {
          font-size: 34px;
          font-weight: 600;
          margin: 0 0 15px;
        }

        .left-subtitle {
          font-size: 16px;
          font-weight: 600;
        }

        .left-intro {
          white-space: nowrap;
          margin: 0 0 20px;
        }
      }
    }

    .right {
      height: 100vh;
      position: relative;

      .login-form {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 50%;
        overflow: hidden;
        background: #ffffff;
        padding: 50px 30px;
        box-shadow: 0 0 2px #999999;
        border-radius: 8px;
      }

      .register-button {
        width: 120px;
        height: 120px;
        display: inline-block;
        background: rgb(196, 214, 252);
        text-align: center;
        line-height: 100px;
        transform: rotate(45deg);
        position: absolute;
        right: -60px;
        top: -60px;

        .register-button-inner {
          color: rgb(74, 96, 179);
          font-weight: 600;
          font-size: 20px;
          transform: rotate(-45deg) translate(-35px, 30px);
          cursor: pointer;
        }
      }

      .title {
        font-size: 34px;
        font-weight: 600;
        text-align: center;
        margin: 20px 0 60px;
      }

      .login-btn {
        display: inherit;
        width: 80%;
        margin: 40px auto 60px;
        cursor: pointer;
      }

      .svg-container {
        position: absolute;
        top: 14px;
        left: 15px;
        z-index: $base-z-index;
        font-size: 16px;
        color: #d7dee3;
        cursor: pointer;
        user-select: none;
      }

      .show-password {
        position: absolute;
        top: 2px;
        right: 25px;
        font-size: 16px;
        color: #d7dee3;
        cursor: pointer;
        user-select: none;
      }

      ::v-deep .agree-button {
        display: flex;

        .el-checkbox__input {
          line-height: 2;
        }

        .el-checkbox__label {
          white-space: normal;
        }
      }

      ::v-deep {
        .el-form-item {
          padding-right: 0;
          margin: 20px 0;
          color: #454545;
          background: transparent;
          border: 1px solid transparent;
          border-radius: 2px;

          &__content {
            min-height: $base-input-height;
            line-height: $base-input-height;
          }

          &__error {
            position: absolute;
            top: 100%;
            left: 18px;
            font-size: $base-font-size-small;
            line-height: 18px;
            color: $base-color-red;
          }
        }

        .el-input {
          box-sizing: border-box;

          input {
            //height: 58px;
            //padding-left: 45px;
            font-size: $base-font-size-default;
            line-height: 58px;
            color: $base-font-color;
            background: #f6f4fc;
            border: 0;
            caret-color: $base-font-color;
          }
        }
      }
    }
  }
</style>
